import resBody from '~/server/utils/resBody'
import { promises as fs } from 'fs'
import { fileURLToPath } from 'url'
import { complierDialogFileContent } from '~/pages/table-diagraming/utils/complier'

// 新增前端页面
export default defineEventHandler(async (event) => {
  const body = await readBody(event)

  const filePath = body.filePath // 获取文件内容

  const fileName = body.fileName // 获取文件名

  const fileContent = body.fileContent // 获取文件内容
  const interactionElements = body.interactionElements // 获取dialog等页面交互

  console.log('111', filePath, fileName, fileContent)

  console.log('222', fileURLToPath(import.meta.url))
  // 获取路径
  try {
    // 创建文件夹 '/Users/soulkey/project/low-code-admin/webapp/src/views/basic-config/views/test-view'
    await fs.mkdir(`${filePath}/${fileName}`, { recursive: true })
    // 在当前文件夹下创建index.vue文件 /Users/soulkey/project/low-code-admin/webapp/src/views/basic-config/views/test-view/index.vue
    await fs.writeFile(`${filePath}/${fileName}/index.vue`, fileContent)
    // 检测是否有dialog等页面交互
    if (interactionElements.length > 0) {
      createInteractionElements(interactionElements, filePath, fileName)
    }

    return resBody.success(true)
  } catch (error: any) {
    console.log('error', error)
    return resBody.error(500, error, '新增前端页面失败')
  }
})

async function createInteractionElements(
  interactionElements: InteractionElementType[],
  filePath: string,
  fileName: string
) {
  await fs.mkdir(`${filePath}/${fileName}/components`, { recursive: true })
  // 创建dialog到components文件夹
  interactionElements.forEach(async (item, index) => {
    if (item.type === 'dialog') {
      await fs.writeFile(
        `${filePath}/${fileName}/components/PageDialog${index + 1}.vue`,
        complierDialogFileContent(item)
      )
    }
  })
}
